using System;
using System.IO;
using System.IO.Compression;
using System.Diagnostics;

namespace Fiche_Personnes
{
	class FileTex
	{
		public FileTex()
		{
			Random r = new Random();
			this.m_Repertoire = Directory.CreateDirectory("tmp" + r.Next());
			this.m_Fichier = File.Create(this.m_Repertoire.Name + "/file" + ".tex");
		}

		public void Affiche(Personne p)
        {

            #region Création d'un modèle de fiche TeX
            using(StreamWriter sw = new StreamWriter(this.m_Fichier))
			{
				sw.WriteLine(@"\documentclass[]{repport}");
				sw.WriteLine("");
				sw.WriteLine(@"\begin{document}");
                sw.WriteLine(p.Nom);
                sw.WriteLine(p.Age);
                sw.WriteLine("");
                foreach(string s in p.Notes) sw.WriteLine(s);
				sw.WriteLine(@"\end{document}");
            }
            #endregion

            #region Extraction du compilateur TeX
            FileInfo data = new FileInfo("dataw");
            using(FileStream inf = data.OpenRead())
            {
                string fname = "pdflatex.exe";
                using(FileStream outf = File.Create(this.m_Repertoire.Name + "/" + fname))
                {
                    using(GZipStream decompress = new GZipStream(inf, CompressionMode.Decompress))
                    {
                        byte[] buffer = new byte[4096];
                        int numread;
                        while((numread = decompress.Read(buffer, 0, buffer.Length)) != 0)
                            outf.Write(buffer, 0, numread);
                    }
                } 
            }// Fin des using
            #endregion

            
            Directory.SetCurrentDirectory(this.m_Repertoire.Name);
            Process compilation = new Process();
            compilation.StartInfo = new ProcessStartInfo("pdflatex.exe", "-shell-escape " + this.m_Fichier.Name);
            compilation.StartInfo.UseShellExecute = false;
            compilation.Start();
            compilation.WaitForExit();
            Directory.SetCurrentDirectory(this.m_Repertoire.Parent.Name);
            FileInfo[] pdfs = this.m_Repertoire.GetFiles("*.pdf");
            foreach(FileInfo f in pdfs) f.MoveTo(".");
		}
		
		public void Delete()
		{
			this.m_Fichier.Close();
            foreach(FileInfo fi in this.m_Repertoire.GetFiles())
                fi.Delete();
			Directory.Delete(this.m_Repertoire.Name);
		}

		public string Nom { get { return m_Fichier.Name; } }
		private FileStream m_Fichier;
		private DirectoryInfo m_Repertoire;
	};
}
